package com.myapp.ruyixing.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.LoginHelper;
import com.myapp.ruyixing.utils.LoginHelper.ILoadInfoListener;
import com.myapp.ruyixing.utils.LoginHelper.ILoginListener;

public class UserFragment extends Fragment implements OnClickListener,
		ILoginListener, ILoadInfoListener {

	private boolean sLoaded = false;

	RequestQueue mQueue;
	ImageLoader mImageLoader;

	@Override
	public void onLoginSuccess() {
		sLoaded = true;
		finishLogin(true, null);
	}

	@Override
	public void onLoginFail(int errorNo) {
		sLoaded = true;
		finishLogin(false, "" + errorNo);
	}

	@Override
	public void onLoadInfoSuccess() {
		sLoaded = true;
		switchViewState(LoginHelper.getInstance().isLogin());
	}

	@Override
	public void onLoadInfoFail(int errorNo) {
		sLoaded = true;
	}

	private void showToast(String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
	}

	private void showLoading(boolean show, String msg) {
		Activity activity = getActivity();
		IShowLoading showLoading = null;
		try {
			showLoading = (IShowLoading) activity;
		} catch (Exception e) {
			return;
		}
		showLoading.showLoading(show, msg);
	}

	private void startLogin(String username, String password) {
		if (TextUtils.isEmpty(username)) {
			showToast("邮箱不能为空！");
			return;
		}
		if (TextUtils.isEmpty(password)) {
			showToast("密码不能为空！");
			return;
		}
		if (LoginHelper.getInstance().doLogin(username, password, this)) {
			showLoading(true, "登录中");
		} else {
			showToast("未知错误");
		}
	}

	private void finishLogin(boolean success, String message) {
		showLoading(false, null);
		if (success) {
			try {
				if (getActivity() instanceof RYXLoginActivity) {
					getActivity().finish();
					showToast("登陆成功！");
					return;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			switchViewState(true);
		} else {
			showToast("登录失败." + message);
		}
	}

	private void switchViewState(boolean isLogin) {
		if (isLogin) {
			String nickname = LoginHelper.getInstance().getUserName();
			if (!TextUtils.isEmpty(nickname)) {
				((TextView) (getView().findViewById(R.id.text_name)))
						.setText(nickname);
			}
			String sex = LoginHelper.getInstance().getUserSex();
			if ("男".equals(sex)) {
				getView().findViewById(R.id.text_name).setSelected(true);
			} else {
				getView().findViewById(R.id.text_name).setSelected(false);
			}
			String avatarUrl = LoginHelper.getInstance().getAvatarUrl();
			if (!TextUtils.isEmpty(avatarUrl)) {
				((NetworkImageView) getView().findViewById(R.id.img_avatar))
						.setImageUrl(avatarUrl, mImageLoader);
			}
			String userCity = LoginHelper.getInstance().getUserCity();
			if (!TextUtils.isEmpty(userCity)) {
				getView().findViewById(R.id.text_city).setVisibility(
						View.VISIBLE);
				((TextView) (getView().findViewById(R.id.text_city)))
						.setText("常居地：" + userCity);
			} else {
				getView().findViewById(R.id.text_city).setVisibility(View.GONE);
			}
			int photo = LoginHelper.getInstance().getUserPhotoCount();
			((TextView) (getView().findViewById(R.id.text_photo)))
					.setText(photo + "");
			int review = LoginHelper.getInstance().getUserReviewCount();
			((TextView) (getView().findViewById(R.id.text_review)))
					.setText(review + "");
			int signin = LoginHelper.getInstance().getUserSigninCount();
			((TextView) (getView().findViewById(R.id.text_signin)))
					.setText(signin + "");

			getView().findViewById(R.id.layout_after_login).setVisibility(
					View.VISIBLE);
			getView().findViewById(R.id.layout_before_login).setVisibility(
					View.GONE);
			if (Config.isShopManagerVersion(getActivity())) {
				((TitleBar) getView().findViewById(R.id.title_bar))
						.setRightIconVisibility(false);
			} else {
				((TitleBar) getView().findViewById(R.id.title_bar))
						.setRightIconVisibility(true);
			}
			if (!sLoaded) {
				LoginHelper.getInstance().loadUserInfo(this);
			}
		} else {
			getView().findViewById(R.id.layout_after_login).setVisibility(
					View.GONE);
			getView().findViewById(R.id.layout_before_login).setVisibility(
					View.VISIBLE);
			((TitleBar) getView().findViewById(R.id.title_bar))
					.setRightIconVisibility(false);
		}
	}

	public UserFragment() {
		// Required empty public constructor
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sLoaded = false;
		mQueue = Volley.newRequestQueue(getActivity());
		mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.fragment_user, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {

		((TitleBar) view.findViewById(R.id.title_bar))
				.setOnRightIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						LoginHelper.getInstance().doLogout();
						switchViewState(false);
					}
				});

		view.findViewById(R.id.btn_login).setOnClickListener(this);
		view.findViewById(R.id.btn_regist).setOnClickListener(this);
		// view.findViewById(R.id.layout_card_balance).setOnClickListener(this);
		// view.findViewById(R.id.layout_consumption_record).setOnClickListener(
		// this);
		// view.findViewById(R.id.btn_modify_password).setOnClickListener(this);
		// view.findViewById(R.id.btn_logout).setOnClickListener(this);

		view.findViewById(R.id.text_dingdan).setOnClickListener(this);
		view.findViewById(R.id.text_shoucang).setOnClickListener(this);
		view.findViewById(R.id.text_jifen).setOnClickListener(this);
		view.findViewById(R.id.text_liuyan).setOnClickListener(this);
		view.findViewById(R.id.text_guanzhu).setOnClickListener(this);
		view.findViewById(R.id.text_fensi).setOnClickListener(this);
		view.findViewById(R.id.layout_qiandao).setOnClickListener(this);
		view.findViewById(R.id.layout_dianping).setOnClickListener(this);
		view.findViewById(R.id.layout_zhaopian).setOnClickListener(this);
		view.findViewById(R.id.btn_sixin).setOnClickListener(this);
		view.findViewById(R.id.layout_ziliao).setOnClickListener(this);
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onResume() {
		switchViewState(LoginHelper.getInstance().isLogin());
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.layout_ziliao:
			intent = new Intent(getActivity(), ModifyUserActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_sixin:
			intent = new Intent(getActivity(), MessageActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_regist:
			intent = new Intent(getActivity(), RegisterActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_login:
			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(getView().findViewById(R.id.edit_email)
					.getWindowToken(), 0);
			startLogin(((EditText) (getView().findViewById(R.id.edit_email)))
					.getText().toString(),
					((EditText) (getView().findViewById(R.id.edit_password)))
							.getText().toString());
			break;
		case R.id.text_dingdan:
			intent = new Intent(getActivity(), OrderActivity.class);
			startActivity(intent);
			break;
		case R.id.text_shoucang:
			intent = new Intent(getActivity(), FavoriteActivity.class);
			startActivity(intent);
			break;
		case R.id.text_jifen:
			intent = new Intent(getActivity(), ScoreActivity.class);
			startActivity(intent);
			break;
		case R.id.text_liuyan:
			intent = new Intent(getActivity(), FeedbackActivity.class);
			startActivity(intent);
			break;
		case R.id.text_guanzhu:
			intent = new Intent(getActivity(), FollowActivity.class);
			startActivity(intent);
			break;
		case R.id.text_fensi:
			intent = new Intent(getActivity(), FansActivity.class);
			startActivity(intent);
			break;
		case R.id.layout_qiandao:
			intent = new Intent(getActivity(), RegistrationActivity.class);
			startActivity(intent);
			break;
		case R.id.layout_dianping:
			intent = new Intent(getActivity(), RemarkActivity.class);
			startActivity(intent);
			break;
		case R.id.layout_zhaopian:
			intent = new Intent(getActivity(), PhotoActivity.class);
			startActivity(intent);
			break;
		// case R.id.btn_logout:
		// LoginHelper.getInstance().doLogout();
		// switchViewState(false);
		// break;
		// case R.id.btn_modify_password:
		// intent = new Intent(getActivity(), ModifyPasswordActivity.class);
		// startActivity(intent);
		// break;
		// case R.id.layout_card_balance:
		// intent = new Intent(getActivity(), CardBalanceActivity.class);
		// startActivity(intent);
		// break;
		// case R.id.layout_consumption_record:
		// intent = new Intent(getActivity(),
		// ConsumptionRecordActivity.class);
		// startActivity(intent);
		// break;

		default:
			break;
		}
	}
}
